package com.easy.controller;

import com.easy.bean.User;
import com.easy.bean.UserAddress;
import com.easy.dao.UserAddressDao;
import com.easy.service.IUserAddressService;
import com.easy.util.LayData;
import com.easy.util.SYS;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("address")
public class UserAddressController {
    @Autowired
    IUserAddressService addressService;
    @RequestMapping("add")
    @ResponseBody
    public LayData add(HttpSession session, UserAddress address){

        int userid=SYS.getLoginUserID(session);
        address.setUserid(userid);
        //检查收货地址的数量不能超过上限
        List list=addressService.getAddressByUserID(userid);
        if (list.size()<SYS.ADDRESS_MAX_NUMBER){
            addressService.add(address);
            return LayData.success(200,"添加成功");
        }else{
            return LayData.success(400,"收货地址已达上限");
        }

    }


    @RequestMapping("edit")
    @ResponseBody
    public LayData edit(UserAddress address) {
        return LayData.success(200,"编辑成功",addressService.edit(address));
    }

    @RequestMapping("delete")
    @ResponseBody
    public LayData delete(int id) {
        return LayData.success(200,"删除成功",addressService.delete(id));
    }

    @RequestMapping("getaddressbyid")
    @ResponseBody
    public LayData getAddressById(int id) {
        return LayData.success(addressService.getAddressByID(id));
    }

    @RequestMapping("getaddressbyuserid")
    @ResponseBody
    public LayData getAddressByUserId(HttpSession session) {
        int userid= SYS.getLoginUserID(session);
        return LayData.success(addressService.getAddressByUserID(userid));
    }

    @RequestMapping("setdefault")
    @ResponseBody
    public LayData setDefault(HttpSession session,int id) {
        int userid= SYS.getLoginUserID(session);
        return LayData.success(addressService.setDefault(userid,id));
    }


}
